import { NavigationGuardNext, RouteLocationNormalized } from 'vue-router';
import NProgress from '@/utils/nprogress';
import router from '@/router';
import { useStore } from '@/stores';

const WHITE_LIST: string[] = ['/', '/signin'];

// 检查是否是白名单路由
const isWhiteListRoute = (path: string): boolean => {
    // 检查静态白名单
    if (WHITE_LIST.includes(path)) {
        return true;
    }
    
    // 检查动态路由 /product/:id
    const productPattern = /^\/product\/[^/]+$/;
    return productPattern.test(path);
}

const redirectToLogin = (to: RouteLocationNormalized, next: NavigationGuardNext): void => {
    const params = new URLSearchParams(to.query as Record<string, string>);
    const queryString = params.toString();
    const redirect = queryString ? `${to.path}?${queryString}` : to.path;
    next(`/signin?redirect=${encodeURIComponent(redirect)}`);
}

export function setupPermission(): void {
    router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): Promise<void> => {
        NProgress.start();
        const store = useStore();
        if (store.auth?.access_token) {
            if (to.path === '/signin') {
                next({ path: '/' });
                NProgress.done();
                return;
            } else {
                if (store.auth?.access_token) {
                    if (to.matched.length === 0) {
                        next(from.name ? { name: from.name } : '/404');
                        return;
                    } else {
                        const title = (to.params.title as string) || (to.query.title as string);
                        if (title) {
                            to.meta.title = title;
                        }
                        next();
                    }
                } else {
                    redirectToLogin(to, next);
                    NProgress.done();
                    return;
                }
            }
        } else {
            if (isWhiteListRoute(to.path)) {
                next();
            } else {
                redirectToLogin(to, next);
                NProgress.done();
            }
        }
    });

    router.afterEach((): void => {
        NProgress.done();
    });
};